
// LoginDlg.cpp : implementation file
//

#include "stdafx.h"
#include "ChatConferencesClient.h"
#include "ChatRoomDialog.h"
#include "LoginDlg.h"
#include "Process.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()


// CLoginDlg dialog




CLoginDlg::CLoginDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CLoginDlg::IDD, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	m_visible = false;
}

void CLoginDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CLoginDlg, CDialog)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_BTN_LOGIN, &CLoginDlg::OnBnClickedBtnLogin)
	ON_BN_CLICKED(IDCANCEL, &CLoginDlg::OnBnClickedCancel)
END_MESSAGE_MAP()


// CLoginDlg message handlers

BOOL CLoginDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	sendType = 0;
	SetDlgItemTextW(IDC_EDIT_SERVER, _T("localhost"));

	globalSock = new CGlobalSocket();
	globalSock->initSocket(_T("localhost"));
	isConnected = false;
	WMSOCKET = globalSock->getWMSOCKET();

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CLoginDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CLoginDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CLoginDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

//*********************************************<<
LRESULT CLoginDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) 
{
	// TODO: Add your specialized code here and/or call the base class
	if (message==WM_SOCKET){
		SockMsg(wParam,lParam);
	}
	return CDialog::WindowProc(message, wParam, lParam);
}
LRESULT CLoginDlg::SockMsg(WPARAM wParam, LPARAM lParam)
{
	if (WSAGETSELECTERROR(lParam))
    {
		 // Display the error and close the socket
         closesocket(wParam);
    }
	switch(WSAGETSELECTEVENT(lParam))
    {
		
		case FD_READ:
			{
				if (!sendType){
					recv(sClient,(char*)&buffLength,sizeof(int),0);
					sendType=1;
				}
				else
				{
					char* buffer=new char[buffLength+1];
					recv(sClient,buffer,buffLength,0);
					buffer[buffLength]='\0';
					sendType=0;
					sReceivedMessage = buffer;
					delete buffer;
					CString sCode = CProcess::getParsedStringAt(sReceivedMessage, 2, '-');
					//MessageBox(sReceivedMessage);
					if( sCode == "201")//Username OK
					{
						//MessageBox (_T("Login Ok"));
						CChatRoomDialog dlg = new CChatRoomDialog();
						ShowWindow(SW_HIDE);
						dlg.initRoom(sUsername,globalSock);
						dlg.DoModal();
						exit(0);
					}
					if (sCode == "202")// Username conflict
					{
						CString mess = sUsername + " is already used";
						MessageBox (mess);
						SetDlgItemTextW(IDC_EDIT_ID, _T(" "));
						return 0;
					}
					
				}
				break;
			}
		case FD_CLOSE:
			{
				closesocket(wParam);
			}
			break;
	}
	return 0;
}

void CLoginDlg::OnBnClickedBtnLogin()
{
	
	CString serverAddress;
	sUsername = _T("");
	GetDlgItemTextW(IDC_EDIT_SERVER, serverAddress);
	GetDlgItemTextW(IDC_EDIT_ID, sUsername);
	sUsername.Trim(' ');
	serverAddress.Trim(' ');
	if(serverAddress == "")
	{
		SetDlgItemTextW(IDC_STATUS_1,_T("* required"));
		return;
	}
	if(sUsername == "")
	{
		SetDlgItemTextW(IDC_STATUS_2,_T("* required"));
		return;
	}
	if(isConnected)
	{
		createPackage(101);
	}
	if(!isConnected)
	{
		globalSock->setServerAddress(serverAddress);
		CString mess = globalSock->connectToServer(serverAddress);
		if( mess != "")
		{
			if(mess == _T("Connect Successful!"))
			{
				isConnected = true;
				GetDlgItem(IDC_EDIT_SERVER)->EnableWindow(false);
				sClient = globalSock->getSockClient();
				int err=WSAAsyncSelect(sClient,m_hWnd,WM_SOCKET,
				FD_READ|FD_ACCEPT|FD_CLOSE);
				if (err)
					MessageBox(_T("Can't call WSAAsyncSelect"));
				createPackage(101);
			}
			else
			{
				MessageBox(mess);
			}
		}
	}
	
}

int CLoginDlg::createPackage(int type)
{
	int retcode;
	CString s = _T("");
	switch(type)
	{
		case 101://Send username
			{
				s += sUsername;
				s += "-1-101-all:seq-Username";

				break;
			}
	}
	if(s != "")
	{
		retcode = sendPackage(s);
	}
	return retcode;
}
int CLoginDlg::sendPackage(CString s)
{
	
	int Len = s.GetLength();
	char* sendBuff=new char[Len+1];
	strncpy(sendBuff,CT2A(s),s.GetLength());
	sendBuff[Len]='\0';
	//Send kich thuoc truoc
	int retcode;
	retcode = send(sClient,(char*)&Len,sizeof(Len),0);
	retcode = send(sClient,(char*)sendBuff,Len,0);
	return retcode;
}

void CLoginDlg::OnBnClickedCancel()
{
	if (sClient!=INVALID_SOCKET)
		shutdown(sClient,SD_BOTH);
	closesocket(sClient);
	WSACleanup();
	exit(0);
}
BOOL CLoginDlg::PreTranslateMessage(MSG* pMsg) 
{
	// TODO: Add your specialized code here and/or call the base class
	if ( pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_RETURN )
	{
		int idCtrl= this->GetFocus()->GetDlgCtrlID();
		if ( idCtrl == IDC_EDIT_ID )
		{
			OnBnClickedBtnLogin();
			return true;
		}
	}
	return CDialog::PreTranslateMessage(pMsg);
}
void CLoginDlg::OnWindowPosChanging(WINDOWPOS FAR* lpwndpos) 
{
	if(!m_visible)
  {
    lpwndpos->flags &= ~SWP_SHOWWINDOW;
  }

  CDialog::OnWindowPosChanging(lpwndpos);
}
//**************************************************>>